package com.yitao.cms.service.product;


import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.json.JSON;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.product.ProductSpecificationDto;
import com.yitao.client.model.product.ProductSpecificationModel;
import com.yitao.client.model.product.QProductSpecificationModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.product.ProductSpecificationAddDto;
import com.yitao.cms.dto.product.ProductSpecificationBasicDto;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.utils.BaseUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  @author skipper
 *  @date 2018-12-22
 *  @desc
 *  @see
 */
@Service
public class ProductSpecificationService extends GenericEntityService<ProductSpecificationModel, ProductSpecificationDto, QProductSpecificationModel> {

    public ProductSpecificationService(EntityManager entityManager) {
        super(entityManager);
    }

    private BaseUtils base = BaseUtils.getInstance();


    /**
     * 其他信息列表信息
     * @param productId
     * @return
     */
    public List<ProductSpecificationDto> getProductSpecificationListByProductId(Long productId){
        return repository.findAll(PredicateBuilder.conjunction()
                .and(()->Q.productId.eq(productId))
                .and(()->Q.isDelete.eq(false))
                .get(),new OrderSpecifier<>(Order.ASC,Q.sort)).stream().map(this::convertEntityToDto).collect(Collectors.toList());
    }

    /**
     * 批量添加产品其他信息
     * @param request
     * @param
     * @return
     */
    @Transactional
    public DataOutput addProductSpecificationList(HttpServletRequest request, ProductSpecificationAddDto productSpecificationAddDto){
        try {
            OperationUserCmsModel userSession = UserSession.getUserSession(request);
            if (userSession == null) {
                return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
            }
            logger.info("批量添加产品其他信息:{}", JSON.toJSONString(productSpecificationAddDto));
            if (productSpecificationAddDto!=null && productSpecificationAddDto.getProductSpecificationBasicDtos().size()>0){
                //根据产品ID删除信息
              Long  productId = productSpecificationAddDto.getProductId();
                if (productId!=null){
                    repository.updateByWhere(Q.productId.eq(productId),it -> it.set(Q.isDelete,true).set(Q.lastUpdateTime,base.getNow()));
                }
                List<ProductSpecificationModel> productSpecificationModelList = new ArrayList<>();
                if (productSpecificationAddDto.getProductSpecificationBasicDtos()!=null && productSpecificationAddDto.getProductSpecificationBasicDtos().size()>0){
                    for (ProductSpecificationBasicDto specificationBasicDto:productSpecificationAddDto.getProductSpecificationBasicDtos()){
                        if (StringUtils.isNotBlank(specificationBasicDto.getSpecificationName())){
                            ProductSpecificationModel productSpecificationModel = new ProductSpecificationModel();
                            if (StringUtils.isBlank(specificationBasicDto.getSpecificationValue())){
                                specificationBasicDto.setSpecificationValue(null);
                            }
                            if (specificationBasicDto.getId()==null||specificationBasicDto.getId()==0L){
                                specificationBasicDto.setId(null);
                            }
                            BeanUtils.copyProperties(specificationBasicDto,productSpecificationModel);
                            productSpecificationModel.setProductId(productId);
                            productSpecificationModel.setDelete(false);
                            productSpecificationModel.setCreateBy(Long.valueOf(userSession.getId()));
                            productSpecificationModel.setCreateTime(base.getNow());
                            productSpecificationModelList.add(productSpecificationModel);
                        }
                    }
                }
                List<ProductSpecificationModel> list =  repository.save(productSpecificationModelList);
               return new DataOutput(list);
            }
            return new DataOutput(CommonStatus.BAD_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加基础信息失败{}",e.getMessage());
            return new DataOutput(CommonStatus.SERVER_ERROR);
        }
    }

}
